import config from "./config";
//ajax请求封装
export const request = params => {
  wx.showNavigationBarLoading();
  wx.showLoading();
  return new Promise((resolve, reject) => {
    wx.request({
      url: config.restUrl + params.url,
      method: params.method ? params.method : "GET",
      dataType: "json",
      header: params.header,
      data: params.data,
      success: function(res) {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        resolve(res.data);
      },
      fail: function(err) {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        console.log(err);
        reject(err);
      }
    });
  });
};

//登陆请求

export const login = userInfo => {
  return new Promise((resolve, reject) => {
    wx.login({
      success: function(res) {
        if (res.code) {
          wx.request({
            url: config.restUrl + "/register",
            method: "POST",
            data: {
              code: res.code,
              nickName: userInfo.nickName,
              gender: userInfo.gender,
              city: userInfo.city,
              province: userInfo.province,
              country: userInfo.country,
              avatarUrl: userInfo.avatarUrl
            },
            success: function(res) {
              // console.log(res);
              resolve(res.data);
            },
            fail: function(err) {
              console.log(err);
              reject(err);
            }
          });
        } else {
          wx.showToast({
            title: "登陆失败"
          });
        }
      }
    });
  });
};

export const showSuccess = text => {
  wx.showToast({
    title: text,
    icon: "success",
    duration: 2000
  });
};
export const showError = text => {
  wx.showToast({
    title: text,
    icon: "none",
    duration: 2000
  });
};

export const getDataSet = (event, key) => {
  return event.currentTarget.dataset[key];
};

export const formatTime = time => {
  var t = new Date(time * 1000);
  return (
    t.getFullYear() +
    "-" +
    (parseInt(t.getMonth()) + 1) +
    "-" +
    t.getDate() +
    " " +
    t.getHours() +
    ":" +
    t.getMinutes()
  );
};
